<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>电子礼金薄</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@400;500;700&display=swap" rel="stylesheet">
  <style>
    body {
      font-family: 'Noto Serif SC', serif;
    }
    /* 自定义图标样式 */
    .icon {
      display: inline-block;
      width: 1em;
      height: 1em;
      stroke-width: 2;
      stroke: currentColor;
      fill: none;
      stroke-linecap: round;
      stroke-linejoin: round;
    }
  </style>
</head>
<body class="bg-stone-100 text-stone-900 antialiased overflow-hidden selection:bg-red-200">
  
  <div class="w-screen h-screen flex flex-col md:flex-row bg-stone-200">
    
    <!-- 控制面板 -->
    <div id="controlPanel" class="w-full md:w-96 h-auto md:h-full bg-red-900 border-r border-red-800 p-6 flex flex-col shadow-2xl z-10 text-red-50 relative overflow-hidden">
      <!-- 装饰性图案 -->
      <div class="absolute inset-0 opacity-5 pointer-events-none" 
           style="background-image: radial-gradient(circle, #fbbf24 1px, transparent 1px); background-size: 20px 20px;">
      </div>

      <div class="relative z-10 mb-4">
        <h1 class="text-3xl font-bold text-amber-400 flex items-center gap-3 font-serif">
          <svg class="icon w-8 h-8" viewBox="0 0 24 24">
            <path d="M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H20v20H6.5a2.5 2.5 0 0 1 0-5H20" />
          </svg>
          电子礼金薄
        </h1>
        <p class="text-red-200/80 text-sm mt-2 mb-2">
          大吉大利 · 喜庆盈门
        </p>
        <div class="text-green-300/80 text-xs mb-4 flex items-center gap-1">
          <svg class="icon w-3 h-3" viewBox="0 0 24 24" fill="currentColor">
            <path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
          自动保存已启用（关闭/刷新时自动备份）
        </div>
        
        <!-- 模式切换 -->
        <div 
          id="modeToggle"
          class="flex items-center gap-3 bg-red-950/40 p-2 rounded-md border border-red-800/30 cursor-pointer hover:bg-red-900/60 transition-colors group select-none"
        >
          <div id="toggleSwitch" class="w-10 h-5 rounded-full relative transition-colors bg-stone-600">
            <div id="toggleDot" class="absolute top-1 w-3 h-3 rounded-full bg-white transition-all shadow-sm left-1"></div>
          </div>
          <div class="flex flex-col">
            <span id="modeText" class="text-xs font-bold text-stone-400">
              36礼金模式 已关闭
            </span>
            <span class="text-[10px] text-red-300/60">
              逢36位自动添加"财百万"
            </span>
          </div>
        </div>
      </div>

      <!-- 表单 -->
      <form id="recordForm" class="relative z-10 flex flex-col gap-4 bg-red-950/30 p-4 rounded-lg border border-red-800/50">
        <div>
          <label class="block text-xs font-medium text-red-200 uppercase tracking-wider mb-1">宾客姓名</label>
          <input
            id="nameInput"
            type="text"
            class="w-full h-10 bg-red-950/50 border border-red-800/50 rounded px-3 text-amber-100 placeholder-red-800/70 focus:ring-1 focus:ring-amber-500/50 focus:border-amber-500/50 outline-none transition-all"
            placeholder="请输入姓名"
            autofocus
          />
        </div>
        
        <div>
          <label class="block text-xs font-medium text-red-200 uppercase tracking-wider mb-1">礼金金额 (元)</label>
          <div class="relative">
            <span class="absolute left-3 top-1/2 -translate-y-1/2 text-red-400">¥</span>
            <input
              id="amountInput"
              type="number"
              class="w-full h-10 bg-red-950/50 border border-red-800/50 rounded pl-7 pr-3 text-amber-100 placeholder-red-800/70 focus:ring-1 focus:ring-amber-500/50 focus:border-amber-500/50 outline-none transition-all font-mono text-lg"
              placeholder="0.00"
              step="0.01"
            />
          </div>
        </div>

        <div>
          <label class="block text-xs font-medium text-red-200 uppercase tracking-wider mb-2">支付方式</label>
          <div class="grid grid-cols-2 gap-2">
            <button
              type="button"
              data-method="现金"
              class="payment-method-btn flex items-center justify-center gap-2 py-2 rounded text-sm transition-all border bg-red-950/30 border-red-800/30 text-red-300 hover:bg-red-900/50"
            >
              <svg class="icon w-3 h-3" viewBox="0 0 24 24">
                <rect x="2" y="7" width="20" height="14" rx="2" />
                <path d="M16 21V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16" />
              </svg>
              现金
            </button>
            <button
              type="button"
              data-method="微信"
              class="payment-method-btn flex items-center justify-center gap-2 py-2 rounded text-sm transition-all border bg-red-950/30 border-red-800/30 text-red-300 hover:bg-red-900/50"
            >
              <svg class="icon w-3 h-3" viewBox="0 0 24 24">
                <rect x="2" y="7" width="20" height="14" rx="2" />
                <path d="M16 21V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16" />
              </svg>
              微信
            </button>
            <button
              type="button"
              data-method="支付宝"
              class="payment-method-btn flex items-center justify-center gap-2 py-2 rounded text-sm transition-all border bg-red-950/30 border-red-800/30 text-red-300 hover:bg-red-900/50"
            >
              <svg class="icon w-3 h-3" viewBox="0 0 24 24">
                <rect x="2" y="7" width="20" height="14" rx="2" />
                <path d="M16 21V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16" />
              </svg>
              支付宝
            </button>
            <button
              type="button"
              data-method="银行卡"
              class="payment-method-btn flex items-center justify-center gap-2 py-2 rounded text-sm transition-all border bg-red-950/30 border-red-800/30 text-red-300 hover:bg-red-900/50"
            >
              <svg class="icon w-3 h-3" viewBox="0 0 24 24">
                <rect x="2" y="7" width="20" height="14" rx="2" />
                <path d="M16 21V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16" />
              </svg>
              银行卡
            </button>
          </div>
        </div>

        <button
          id="submitBtn"
          type="submit"
          class="w-full py-3 rounded font-bold text-lg flex items-center justify-center gap-2 transition-all shadow-lg mt-2 bg-red-800/50 text-red-500 cursor-not-allowed"
        >
          <svg class="icon w-5 h-5" viewBox="0 0 24 24">
            <circle cx="12" cy="12" r="10" />
            <path d="M12 8v8M8 12h8" />
          </svg>
          记一笔
        </button>
      </form>

      <!-- 仪表板 -->
      <div class="mt-4 flex-grow relative z-10 flex flex-col gap-3 overflow-y-auto">
        <!-- 总金额 -->
        <div class="bg-red-950/40 rounded-lg p-4 border border-red-800/30 shrink-0">
          <div class="flex items-center gap-2 text-red-200 mb-1">
            <svg class="icon w-4 h-4" viewBox="0 0 24 24">
              <circle cx="12" cy="12" r="10" />
              <path d="M12 6v6l4 2" />
            </svg>
            <span class="text-sm font-medium">全员总金额</span>
          </div>
          <div id="grandTotal" class="text-3xl font-bold text-amber-400 font-mono tracking-tight">
            ¥ 0
          </div>
          <div class="mt-2 pt-2 border-t border-red-800/30 flex justify-between items-center text-xs text-red-300">
            <span>总人数</span>
            <span id="totalCount" class="font-mono font-bold">0 人</span>
          </div>
        </div>

        <!-- 支付方式汇总 -->
        <div class="bg-red-950/20 rounded-lg p-3 border border-red-800/20 text-xs shrink-0">
          <h3 class="text-red-300 mb-2 font-medium flex items-center gap-2">
            <svg class="icon w-3 h-3" viewBox="0 0 24 24">
              <rect x="2" y="7" width="20" height="14" rx="2" />
              <path d="M16 21V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16" />
            </svg>
            支付方式汇总 (分类)
          </h3>
          <div id="paymentStats" class="space-y-1.5">
            <div class="text-red-800/50 italic text-center py-1">暂无数据</div>
          </div>
        </div>

        <!-- 自动备份开关 -->
        <div class="bg-red-950/20 rounded-lg p-3 border border-red-800/20 text-xs shrink-0">
          <div 
            id="autoBackupToggle"
            class="flex items-center gap-3 cursor-pointer hover:bg-red-900/30 p-2 rounded transition-colors group select-none"
          >
            <div id="autoBackupSwitch" class="w-8 h-4 rounded-full relative transition-colors bg-stone-600">
              <div id="autoBackupDot" class="absolute top-0.5 w-3 h-3 rounded-full bg-white transition-all shadow-sm left-0.5"></div>
            </div>
            <div class="flex flex-col flex-1">
              <span id="autoBackupText" class="text-xs font-medium text-red-200">
                自动备份 (已关闭)
              </span>
              <span class="text-[10px] text-red-300/60">
                每10条记录自动下载备份
              </span>
            </div>
          </div>
        </div>

        <!-- 手动备份 -->
        <button
          id="exportBtn"
          class="w-full py-2 bg-stone-700/50 hover:bg-stone-700 border border-stone-600 text-stone-200 rounded flex items-center justify-center gap-2 text-sm transition-colors mt-auto shrink-0"
        >
          <svg class="icon w-4 h-4" viewBox="0 0 24 24">
            <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
            <polyline points="7 10 12 15 17 10" />
            <line x1="12" y1="15" x2="12" y2="3" />
          </svg>
          手动备份下载
        </button>
      </div>
      
      <div class="mt-4 relative z-10 pt-2 border-t border-red-800/30 shrink-0">
        <button 
          id="clearAllBtn"
          class="w-full py-2 text-red-400 hover:text-red-200 flex items-center justify-center gap-2 text-xs transition-colors opacity-60 hover:opacity-100 hidden"
        >
          <svg class="icon w-3 h-3" viewBox="0 0 24 24">
            <polyline points="3 6 5 6 21 6" />
            <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
          </svg>
          清空所有数据
        </button>
      </div>
    </div>

    <!-- 账本查看器 -->
    <div id="bookViewer" class="flex-1 bg-stone-200 relative overflow-hidden flex flex-col h-full items-center justify-center p-2 md:p-6">
      
      <!-- 纸张 -->
      <div class="bg-[#fdfbf9] w-full max-w-[1400px] h-full md:h-[95%] shadow-2xl rounded-sm flex flex-col overflow-hidden relative border border-stone-300">
        
        <!-- 头部装饰 -->
        <div class="h-2 bg-red-900 w-full shrink-0"></div>
        <div class="h-1 bg-red-800 w-full mt-0.5 opacity-60 shrink-0"></div>

        <!-- 纸张内容 -->
        <div class="flex-1 px-4 py-4 md:px-8 md:py-6 flex flex-col overflow-hidden">
          
          <!-- 头部 -->
          <div class="flex justify-between items-end mb-4 border-b-2 border-red-900/20 pb-2 shrink-0">
            <h2 class="text-xl md:text-3xl font-serif font-bold text-red-900 flex items-center gap-3">
              <span class="w-10 h-10 bg-red-900 text-amber-100 rounded flex items-center justify-center text-lg border-2 border-double border-amber-500 shadow-sm">礼</span>
              礼金详单
            </h2>
            <div class="text-stone-500 font-serif text-sm flex items-baseline gap-1">
              第 <span id="currentPageDisplay" class="text-red-900 font-bold text-2xl font-mono mx-1">1</span> / <span id="totalPagesDisplay">1</span> 页
            </div>
          </div>

          <!-- 矩阵布局 (12列 x 3行) -->
          <div class="flex-1 flex flex-col border-2 border-red-900 text-stone-800 shadow-sm overflow-hidden select-none">
            
            <!-- 第1行: 姓名 (垂直文字) - 40% 高度 -->
            <div id="nameRow" class="h-[40%] flex border-b border-red-900 w-full">
              <!-- 动态生成 -->
            </div>

            <!-- 第2行: 金额 (垂直数字) - 45% 高度 -->
            <div id="amountRow" class="h-[45%] flex border-b border-red-900 w-full bg-red-50/5">
              <!-- 动态生成 -->
            </div>

            <!-- 第3行: 支付方式 (水平/紧凑) - 15% 高度 -->
            <div id="paymentRow" class="h-[15%] flex w-full bg-stone-100/30">
              <!-- 动态生成 -->
            </div>

          </div>
            
          <!-- 页脚 / 小计 -->
          <div class="mt-auto pt-4 flex justify-between items-center shrink-0">
            <div class="text-red-900/60 text-xs font-serif">
              * 严谨记录 · 账目分明
            </div>
            <div class="bg-red-50 border border-red-200 rounded-sm py-2 px-4 shadow-sm flex items-center gap-4">
              <span class="text-red-900 font-serif font-bold text-sm md:text-base">
                本页合计
              </span>
              <span id="pageSubtotal" class="font-mono text-xl md:text-2xl font-bold text-red-700">
                ¥ 0.00
              </span>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页控制 -->
      <div class="mt-4 flex items-center gap-6 z-10">
        <button
          id="prevPageBtn"
          class="w-10 h-10 md:w-12 md:h-12 rounded-full shadow-xl flex items-center justify-center transition-all border border-stone-100 bg-stone-300 text-stone-500 cursor-not-allowed opacity-50"
        >
          <svg class="icon w-5 h-5 md:w-6 md:h-6" viewBox="0 0 24 24">
            <polyline points="15 18 9 12 15 6" />
          </svg>
        </button>
        
        <div class="px-4 py-1.5 md:px-6 md:py-2 bg-stone-800/80 backdrop-blur border border-stone-600 rounded-full text-xs md:text-sm font-bold shadow-lg text-stone-100 font-mono tracking-widest">
          <span id="pageIndicator">1 / 1</span>
        </div>

        <button
          id="nextPageBtn"
          class="w-10 h-10 md:w-12 md:h-12 rounded-full shadow-xl flex items-center justify-center transition-all border border-stone-100 bg-stone-300 text-stone-500 cursor-not-allowed opacity-50"
        >
          <svg class="icon w-5 h-5 md:w-6 md:h-6" viewBox="0 0 24 24">
            <polyline points="9 18 15 12 9 6" />
          </svg>
        </button>
      </div>

    </div>
  </div>

  <script>
    // 常量
    const PAGE_SIZE = 12;
    const STORAGE_KEY_RECORDS = 'gift_book_records';
    const STORAGE_KEY_36MODE = 'gift_book_36mode';

    // 状态
    let records = [];
    let is36Mode = false;
    let currentPage = 1;
    let selectedPaymentMethod = '现金';
    let autoBackupEnabled = false;
    let autoBackupInterval = null;
    let lastBackupCount = 0;
    let fileHandle = null; // File System Access API 文件句柄
    let lastSaveTime = 0; // 上次保存时间，避免频繁保存

    // 初始化
    function init() {
      // 从localStorage加载数据
      try {
        const savedRecords = localStorage.getItem(STORAGE_KEY_RECORDS);
        records = savedRecords ? JSON.parse(savedRecords) : [];
      } catch (e) {
        console.error('Failed to load records', e);
        records = [];
      }

      try {
        is36Mode = localStorage.getItem(STORAGE_KEY_36MODE) === 'true';
      } catch (e) {
        is36Mode = false;
      }

      try {
        autoBackupEnabled = localStorage.getItem('gift_book_autobackup') === 'true';
        lastBackupCount = parseInt(localStorage.getItem('gift_book_lastbackup') || '0', 10);
      } catch (e) {
        autoBackupEnabled = false;
        lastBackupCount = 0;
      }

      // 初始化UI
      updateModeToggle();
      updateAutoBackupToggle();
      updatePaymentMethodButtons();
      updateSubmitButton();
      updateStats();
      renderPage();
      setupEventListeners();
      setupAutoSave();
    }

    // 设置事件监听器
    function setupEventListeners() {
      // 表单提交
      document.getElementById('recordForm').addEventListener('submit', handleAddRecord);
      
      // 支付方式按钮
      document.querySelectorAll('.payment-method-btn').forEach(btn => {
        btn.addEventListener('click', () => {
          selectedPaymentMethod = btn.dataset.method;
          updatePaymentMethodButtons();
          updateSubmitButton();
        });
      });

      // 模式切换
      document.getElementById('modeToggle').addEventListener('click', toggleMode);

      // 自动备份切换
      document.getElementById('autoBackupToggle').addEventListener('click', toggleAutoBackup);

      // 分页按钮
      document.getElementById('prevPageBtn').addEventListener('click', () => changePage(-1));
      document.getElementById('nextPageBtn').addEventListener('click', () => changePage(1));

      // 导出按钮
      document.getElementById('exportBtn').addEventListener('click', () => exportData(records));

      // 清空按钮
      document.getElementById('clearAllBtn').addEventListener('click', clearAll);

      // 输入框变化
      document.getElementById('nameInput').addEventListener('input', updateSubmitButton);
      document.getElementById('amountInput').addEventListener('input', updateSubmitButton);
    }

    // 添加记录
    function handleAddRecord(e) {
      e.preventDefault();
      const name = document.getElementById('nameInput').value.trim();
      const amount = parseFloat(document.getElementById('amountInput').value);

      if (!name || !amount || amount <= 0) return;

      let currentList = [...records];

      // 36礼金模式逻辑
      if (is36Mode && (currentList.length + 1) % 36 === 0) {
        const specialRecord = {
          id: Date.now().toString() + '_auto',
          name: '财百万',
          amount: 1000000,
          paymentMethod: '现金',
          timestamp: Date.now(),
        };
        currentList.push(specialRecord);
      }

      const newRecord = {
        id: Date.now().toString(),
        name,
        amount,
        paymentMethod: selectedPaymentMethod,
        timestamp: Date.now(),
      };

      const updatedList = [...currentList, newRecord];
      records = updatedList;
      saveRecords();

      // 自动跳转到新页
      const newTotalPages = Math.max(1, Math.ceil(updatedList.length / PAGE_SIZE));
      if (newTotalPages > currentPage) {
        currentPage = newTotalPages;
      }

      // 清空表单
      document.getElementById('nameInput').value = '';
      document.getElementById('amountInput').value = '';
      updateSubmitButton();

      // 更新UI
      updateStats();
      renderPage();

      // 智能备份：只在开启自动备份且满足条件时备份
      checkAutoBackup(updatedList.length);
      
      // 触发自动保存（延迟执行，避免阻塞UI）
      setTimeout(() => {
        if (!document.hidden) {
          silentSaveToFile();
        }
      }, 500);
    }

    // 删除记录
    function deleteRecord(id) {
      const confirmMsg = autoBackupEnabled 
        ? '确定要删除这条记录吗？删除后金额将重新计算。'
        : '确定要删除这条记录吗？删除后金额将重新计算。';
      
      if (window.confirm(confirmMsg)) {
        const updatedList = records.filter(r => r.id !== id);
        records = updatedList;
        saveRecords();

        // 调整页码
        const newTotalPages = Math.max(1, Math.ceil(updatedList.length / PAGE_SIZE));
        if (currentPage > newTotalPages) {
          currentPage = newTotalPages;
        }

        updateStats();
        renderPage();

        // 智能备份：只在开启自动备份且满足条件时备份
        checkAutoBackup(updatedList.length);
        
        // 触发自动保存
        setTimeout(() => {
          if (!document.hidden) {
            silentSaveToFile();
          }
        }, 500);
      }
    }

    // 清空所有
    function clearAll() {
      if (window.confirm('确定要清空所有记录吗？此操作无法撤销！')) {
        records = [];
        currentPage = 1;
        localStorage.removeItem(STORAGE_KEY_RECORDS);
        updateStats();
        renderPage();
      }
    }

    // 切换模式
    function toggleMode() {
      is36Mode = !is36Mode;
      localStorage.setItem(STORAGE_KEY_36MODE, String(is36Mode));
      updateModeToggle();
    }

    // 切换自动备份
    function toggleAutoBackup() {
      autoBackupEnabled = !autoBackupEnabled;
      localStorage.setItem('gift_book_autobackup', String(autoBackupEnabled));
      updateAutoBackupToggle();
      
      if (!autoBackupEnabled) {
        lastBackupCount = records.length;
        localStorage.setItem('gift_book_lastbackup', String(lastBackupCount));
      }
    }

    // 更新自动备份切换UI
    function updateAutoBackupToggle() {
      const switchEl = document.getElementById('autoBackupSwitch');
      const dotEl = document.getElementById('autoBackupDot');
      const textEl = document.getElementById('autoBackupText');

      if (autoBackupEnabled) {
        switchEl.classList.remove('bg-stone-600');
        switchEl.classList.add('bg-green-600');
        dotEl.classList.remove('left-0.5');
        dotEl.classList.add('left-4');
        textEl.textContent = '自动备份 (已开启)';
        textEl.classList.remove('text-red-200');
        textEl.classList.add('text-green-300');
      } else {
        switchEl.classList.remove('bg-green-600');
        switchEl.classList.add('bg-stone-600');
        dotEl.classList.remove('left-4');
        dotEl.classList.add('left-0.5');
        textEl.textContent = '自动备份 (已关闭)';
        textEl.classList.remove('text-green-300');
        textEl.classList.add('text-red-200');
      }
    }

    // 智能备份检查
    function checkAutoBackup(currentCount) {
      if (!autoBackupEnabled) {
        return; // 未开启自动备份，不执行
      }

      // 每10条记录备份一次
      const BACKUP_INTERVAL = 10;
      const recordsSinceLastBackup = currentCount - lastBackupCount;
      
      if (recordsSinceLastBackup >= BACKUP_INTERVAL) {
        exportData(records);
        lastBackupCount = currentCount;
        localStorage.setItem('gift_book_lastbackup', String(lastBackupCount));
      }
    }

    // 更新模式切换UI
    function updateModeToggle() {
      const switchEl = document.getElementById('toggleSwitch');
      const dotEl = document.getElementById('toggleDot');
      const textEl = document.getElementById('modeText');

      if (is36Mode) {
        switchEl.classList.remove('bg-stone-600');
        switchEl.classList.add('bg-amber-500');
        dotEl.classList.remove('left-1');
        dotEl.classList.add('left-6');
        textEl.textContent = '36礼金模式 已开启';
        textEl.classList.remove('text-stone-400');
        textEl.classList.add('text-amber-400');
      } else {
        switchEl.classList.remove('bg-amber-500');
        switchEl.classList.add('bg-stone-600');
        dotEl.classList.remove('left-6');
        dotEl.classList.add('left-1');
        textEl.textContent = '36礼金模式 已关闭';
        textEl.classList.remove('text-amber-400');
        textEl.classList.add('text-stone-400');
      }
    }

    // 更新支付方式按钮
    function updatePaymentMethodButtons() {
      document.querySelectorAll('.payment-method-btn').forEach(btn => {
        if (btn.dataset.method === selectedPaymentMethod) {
          btn.classList.remove('bg-red-950/30', 'border-red-800/30', 'text-red-300');
          btn.classList.add('bg-amber-600/90', 'border-amber-500', 'text-white', 'shadow-lg');
        } else {
          btn.classList.remove('bg-amber-600/90', 'border-amber-500', 'text-white', 'shadow-lg');
          btn.classList.add('bg-red-950/30', 'border-red-800/30', 'text-red-300');
        }
      });
    }

    // 更新提交按钮
    function updateSubmitButton() {
      const name = document.getElementById('nameInput').value.trim();
      const amount = document.getElementById('amountInput').value;
      const btn = document.getElementById('submitBtn');

      if (!name || !amount) {
        btn.classList.add('bg-red-800/50', 'text-red-500', 'cursor-not-allowed');
        btn.classList.remove('bg-amber-600', 'text-white', 'hover:bg-amber-500');
        btn.disabled = true;
      } else {
        btn.classList.remove('bg-red-800/50', 'text-red-500', 'cursor-not-allowed');
        btn.classList.add('bg-amber-600', 'text-white', 'hover:bg-amber-500');
        btn.disabled = false;
      }
    }

    // 更新统计
    function updateStats() {
      const grandTotal = records.reduce((sum, r) => sum + r.amount, 0);
      const totalCount = records.length;

      document.getElementById('grandTotal').textContent = `¥ ${grandTotal.toLocaleString('zh-CN', { minimumFractionDigits: 0 })}`;
      document.getElementById('totalCount').textContent = `${totalCount} 人`;

      // 支付方式统计
      const paymentStats = records.reduce((acc, curr) => {
        acc[curr.paymentMethod] = (acc[curr.paymentMethod] || 0) + curr.amount;
        return acc;
      }, {});

      const statsContainer = document.getElementById('paymentStats');
      if (Object.keys(paymentStats).length === 0) {
        statsContainer.innerHTML = '<div class="text-red-800/50 italic text-center py-1">暂无数据</div>';
      } else {
        statsContainer.innerHTML = Object.entries(paymentStats)
          .map(([method, total]) => `
            <div class="flex justify-between items-center">
              <span class="text-red-200/80">${method}</span>
              <span class="font-mono text-amber-100">¥ ${total.toLocaleString()}</span>
            </div>
          `).join('');
      }

      // 显示/隐藏清空按钮
      const clearBtn = document.getElementById('clearAllBtn');
      if (totalCount > 0) {
        clearBtn.classList.remove('hidden');
      } else {
        clearBtn.classList.add('hidden');
      }
    }

    // 渲染页面
    function renderPage() {
      const totalPages = Math.max(1, Math.ceil(records.length / PAGE_SIZE));
      const safeCurrentPage = Math.min(Math.max(1, currentPage), totalPages);
      currentPage = safeCurrentPage;

      const startIndex = (currentPage - 1) * PAGE_SIZE;
      const currentRecords = records.slice(startIndex, startIndex + PAGE_SIZE);

      // 填充到12条
      const filledRecords = [...currentRecords];
      while (filledRecords.length < PAGE_SIZE) {
        filledRecords.push(null);
      }

      // 计算本页小计
      const pageSubtotal = currentRecords.reduce((sum, r) => sum + r.amount, 0);

      // 更新页码显示
      document.getElementById('currentPageDisplay').textContent = currentPage;
      document.getElementById('totalPagesDisplay').textContent = totalPages;
      document.getElementById('pageIndicator').textContent = `${currentPage} / ${totalPages}`;
      document.getElementById('pageSubtotal').textContent = `¥ ${pageSubtotal.toLocaleString('zh-CN', { minimumFractionDigits: 2 })}`;

      // 渲染姓名行
      const nameRow = document.getElementById('nameRow');
      nameRow.innerHTML = filledRecords.map((record, idx) => {
        if (record) {
          const isSpecial = record.name === '财百万';
          return `
            <div class="w-[8.333333%] border-r border-red-900 last:border-r-0 relative group hover:bg-red-50/30 transition-colors py-2 flex justify-center items-center overflow-hidden">
              <button 
                onclick="deleteRecord('${record.id}')"
                class="absolute top-1 right-1 text-red-300 hover:text-red-600 opacity-0 group-hover:opacity-100 transition-opacity z-10"
                title="删除此记录"
              >
                <svg class="w-4 h-4 md:w-5 md:h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                  <circle cx="12" cy="12" r="10" />
                  <line x1="15" y1="9" x2="9" y2="15" />
                  <line x1="9" y1="9" x2="15" y2="15" />
                </svg>
              </button>
              <span class="text-lg md:text-2xl font-serif font-bold ${isSpecial ? 'text-amber-600' : 'text-stone-900'} tracking-[0.3em] leading-relaxed select-text" style="writing-mode: vertical-rl; text-orientation: upright;">
                ${record.name}
              </span>
            </div>
          `;
        } else {
          return '<div class="w-[8.333333%] border-r border-red-900 last:border-r-0 flex justify-center items-center"><div class="w-px h-1/3 bg-red-900/10"></div></div>';
        }
      }).join('');

      // 渲染金额行
      const amountRow = document.getElementById('amountRow');
      amountRow.innerHTML = filledRecords.map((record, idx) => {
        if (record) {
          const isSpecial = record.name === '财百万';
          const amountStr = record.amount.toString();
          let fontSize = 'text-lg md:text-2xl';
          if (amountStr.length > 6) fontSize = 'text-sm md:text-base';
          else if (amountStr.length > 4) fontSize = 'text-base md:text-lg';

          return `
            <div class="w-[8.333333%] border-r border-red-900 last:border-r-0 flex flex-col items-center justify-center hover:bg-red-50/50 transition-colors py-2 overflow-hidden relative group">
              <div class="font-mono font-bold ${isSpecial ? 'text-amber-600' : 'text-red-800'} tracking-widest ${fontSize}" style="writing-mode: vertical-rl; text-orientation: upright;">
                ${record.amount}
              </div>
            </div>
          `;
        } else {
          return '<div class="w-[8.333333%] border-r border-red-900 last:border-r-0 flex justify-center items-center"><div class="w-px h-1/4 bg-red-900/10"></div></div>';
        }
      }).join('');

      // 渲染支付方式行
      const paymentRow = document.getElementById('paymentRow');
      paymentRow.innerHTML = filledRecords.map((record, idx) => {
        if (record) {
          let badgeClass = 'text-stone-600 bg-stone-200/50';
          if (record.paymentMethod === '现金') badgeClass = 'text-amber-800 bg-amber-100/50';
          else if (record.paymentMethod.includes('微信')) badgeClass = 'text-green-800 bg-green-100/50';
          else if (record.paymentMethod.includes('支付宝')) badgeClass = 'text-blue-800 bg-blue-100/50';

          return `
            <div class="w-[8.333333%] border-r border-red-900 last:border-r-0 flex items-center justify-center hover:bg-red-50/50 transition-colors p-1 overflow-hidden">
              <span class="text-[10px] md:text-xs font-medium px-1.5 py-0.5 rounded-full whitespace-nowrap scale-90 md:scale-100 origin-center ${badgeClass}">
                ${record.paymentMethod}
              </span>
            </div>
          `;
        } else {
          return '<div class="w-[8.333333%] border-r border-red-900 last:border-r-0"></div>';
        }
      }).join('');

      // 更新分页按钮
      const prevBtn = document.getElementById('prevPageBtn');
      const nextBtn = document.getElementById('nextPageBtn');

      if (currentPage === 1) {
        prevBtn.classList.add('bg-stone-300', 'text-stone-500', 'cursor-not-allowed', 'opacity-50');
        prevBtn.classList.remove('bg-white', 'text-red-900', 'hover:bg-red-50', 'hover:scale-110', 'hover:border-red-200');
        prevBtn.disabled = true;
      } else {
        prevBtn.classList.remove('bg-stone-300', 'text-stone-500', 'cursor-not-allowed', 'opacity-50');
        prevBtn.classList.add('bg-white', 'text-red-900', 'hover:bg-red-50', 'hover:scale-110', 'hover:border-red-200');
        prevBtn.disabled = false;
      }

      if (currentPage === totalPages) {
        nextBtn.classList.add('bg-stone-300', 'text-stone-500', 'cursor-not-allowed', 'opacity-50');
        nextBtn.classList.remove('bg-white', 'text-red-900', 'hover:bg-red-50', 'hover:scale-110', 'hover:border-red-200');
        nextBtn.disabled = true;
      } else {
        nextBtn.classList.remove('bg-stone-300', 'text-stone-500', 'cursor-not-allowed', 'opacity-50');
        nextBtn.classList.add('bg-white', 'text-red-900', 'hover:bg-red-50', 'hover:scale-110', 'hover:border-red-200');
        nextBtn.disabled = false;
      }
    }

    // 切换页面
    function changePage(delta) {
      const totalPages = Math.max(1, Math.ceil(records.length / PAGE_SIZE));
      const newPage = Math.max(1, Math.min(totalPages, currentPage + delta));
      if (newPage !== currentPage) {
        currentPage = newPage;
        renderPage();
      }
    }

    // 保存记录
    function saveRecords() {
      try {
        localStorage.setItem(STORAGE_KEY_RECORDS, JSON.stringify(records));
      } catch (e) {
        console.error('Failed to save records', e);
      }
    }

    // 导出数据（手动备份）
    function exportData(currentRecords = records) {
      const csvContent = generateCSVContent(currentRecords);
      const bom = '\uFEFF'; // BOM for Excel UTF-8
      const blob = new Blob([bom + csvContent], { type: 'text/csv;charset=utf-8;' });

      // 触发下载
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      const timeStr = new Date().toISOString().replace(/T/, '_').replace(/:/g, '-').split('.')[0];
      link.setAttribute('download', `礼金账本_手动备份_${timeStr}.csv`);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      
      // 更新保存计数
      localStorage.setItem('gift_book_saved_count', String(currentRecords.length));
    }

    // 静默保存到文件（不触发下载弹窗）
    async function silentSaveToFile() {
      // 避免频繁保存（至少间隔1秒）
      const now = Date.now();
      if (now - lastSaveTime < 1000) {
        return;
      }
      lastSaveTime = now;

      try {
        const csvContent = generateCSVContent(records);
        const bom = '\uFEFF';
        const blob = new Blob([bom + csvContent], { type: 'text/csv;charset=utf-8;' });

        // 尝试使用 File System Access API（如果支持）
        if ('showSaveFilePicker' in window && fileHandle) {
          try {
            const writable = await fileHandle.createWritable();
            await writable.write(blob);
            await writable.close();
            console.log('文件已自动保存');
            return;
          } catch (e) {
            console.log('File System Access API 保存失败，使用备用方案', e);
          }
        }

        // 备用方案：使用隐藏的下载链接
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.style.display = 'none';
        link.setAttribute('download', `礼金账本_自动保存_${new Date().toISOString().replace(/T/, '_').replace(/:/g, '-').split('.')[0]}.csv`);
        document.body.appendChild(link);
        
        // 尝试触发下载（在页面卸载时可能被浏览器阻止）
        try {
          link.click();
        } catch (e) {
          console.log('自动下载被阻止，但数据已准备好', e);
        }
        
        // 延迟清理，确保下载能开始
        setTimeout(() => {
          document.body.removeChild(link);
          URL.revokeObjectURL(url);
        }, 100);
      } catch (e) {
        console.error('自动保存失败', e);
      }
    }

    // 生成CSV内容
    function generateCSVContent(currentRecords) {
      // 1. 详情部分
      const headers = "ID,姓名,金额,支付方式,记录时间\n";
      const rows = currentRecords.map(r => 
        `"${r.id}","${r.name}","${r.amount}","${r.paymentMethod}","${new Date(r.timestamp).toLocaleString()}"`
      ).join("\n");

      // 2. 汇总部分 (分类)
      const stats = currentRecords.reduce((acc, curr) => {
        acc[curr.paymentMethod] = (acc[curr.paymentMethod] || 0) + curr.amount;
        return acc;
      }, {});

      const totalAmount = currentRecords.reduce((sum, r) => sum + r.amount, 0);

      let summarySection = "\n\n--- 统计汇总 (分类) ---\n分类,金额\n";
      Object.entries(stats).forEach(([method, amount]) => {
        summarySection += `${method},${amount}\n`;
      });
      summarySection += `总计,${totalAmount}\n`;

      return headers + rows + summarySection;
    }

    // 设置自动保存
    function setupAutoSave() {
      // 1. 页面可见性变化时保存（切换到其他标签页、最小化等）
      document.addEventListener('visibilitychange', () => {
        if (document.hidden && records.length > 0) {
          // 页面隐藏时自动保存
          silentSaveToFile();
        }
      });

      // 2. 页面卸载前保存（关闭标签页、刷新等）
      window.addEventListener('beforeunload', (e) => {
        if (records.length > 0) {
          // 尝试同步保存（使用 sendBeacon 或同步方式）
          try {
            const csvContent = generateCSVContent(records);
            const bom = '\uFEFF';
            const blob = new Blob([bom + csvContent], { type: 'text/csv;charset=utf-8;' });
            
            // 使用 sendBeacon 尝试发送（虽然不能直接下载，但可以保存数据）
            if (navigator.sendBeacon) {
              const timeStr = new Date().toISOString().replace(/T/, '_').replace(/:/g, '-').split('.')[0];
              const formData = new FormData();
              formData.append('file', blob, `礼金账本_自动保存_${timeStr}.csv`);
              // 注意：这需要服务器支持，如果没有服务器，这个会失败但不影响其他功能
            }
            
            // 尝试触发下载（可能被浏览器阻止）
            silentSaveToFile();
          } catch (err) {
            console.error('页面卸载时保存失败', err);
          }
        }
      });

      // 3. 页面隐藏时保存（pagehide 事件，比 beforeunload 更可靠）
      window.addEventListener('pagehide', () => {
        if (records.length > 0) {
          silentSaveToFile();
        }
      });

      // 4. 定期保存（每30秒，如果页面可见且有新数据）
      setInterval(() => {
        if (!document.hidden && records.length > 0) {
          // 检查是否有新数据（通过比较记录数量）
          const savedCount = parseInt(localStorage.getItem('gift_book_saved_count') || '0', 10);
          if (records.length !== savedCount) {
            silentSaveToFile();
            localStorage.setItem('gift_book_saved_count', String(records.length));
          }
        }
      }, 30000); // 30秒
    }

    // 初始化文件句柄（如果用户之前选择过文件）
    async function initFileHandle() {
      try {
        const savedHandle = localStorage.getItem('gift_book_file_handle');
        if (savedHandle && 'showSaveFilePicker' in window) {
          // File System Access API 不支持序列化句柄，需要用户重新选择
          // 但我们可以提示用户选择文件位置
        }
      } catch (e) {
        console.log('文件句柄初始化失败', e);
      }
    }

    // 将deleteRecord暴露到全局作用域，以便onclick使用
    window.deleteRecord = deleteRecord;

    // 启动应用
    init();
    initFileHandle();
  </script>
</body>
</html>

